package setting

import (
	"../common"
	"../web"
	"fmt"
	"strconv"
	"strings"
)

type SetKeyPartsObj struct {
	common.BaseHandler
}

type DeleteKeyPartsObj struct {
	common.BaseHandler
}

func (self *SetKeyPartsObj) Prepare() {
	items := *common.FetchAllRowsPtr(
		`SELECT ITEM, ISNULL(DESCRIP,'') 
           FROM SFC_ITEMS(NOLOCK) 
          ORDER BY ITEM`,
		self.Usr.Conn, new(common.ItemDesc))

	stations := *common.FetchAllRowsPtr(
		`SELECT STATION, ''
           FROM SFC_STATION(NOLOCK) 
          ORDER BY STATION`,
		self.Usr.Conn, new(common.Station))

	self.TmplData["items"] = items
	self.TmplData["stations"] = stations
}

func (self *SetKeyPartsObj) ParameterCheck() bool {
	c_item := self.Ctx.Params["item"]
	c_stat := self.Ctx.Params["station"]
	c_name := strings.TrimSpace(self.Ctx.Params["partname"])
	c_desc := strings.TrimSpace(self.Ctx.Params["desc"])
	c_barc := strings.TrimSpace(self.Ctx.Params["barcode"])
	c_leng := strings.TrimSpace(self.Ctx.Params["leng"])
	c_iqty := strings.TrimSpace(self.Ctx.Params["qty"])
	if c_item == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the item.")
		return false
	}

	parts := *common.FetchAllRowsPtr(
		`SELECT ROW_NUMBER() OVER(PARTITION BY STATION ORDER BY IDX ASC),
                 ITEM,STATION,PARTNAME,ISNULL(BARCODE, ''), 
                 CASE CONVERT(CHAR(2),LENG) WHEN '-1' THEN '' ELSE CONVERT(CHAR(2),LENG) END,QTY
           FROM SFC_PARTSETTING(NOLOCK) 
          WHERE ITEM=?`,
		self.Usr.Conn, new(common.PartInfo), c_item)

	self.TmplData["parts"] = parts

	if c_stat == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the Station.")
		return false
	}
	if c_name == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the part name.")
		return false
	}
	i_cleng := -1
	if c_leng != "" {
		i_leng, err := strconv.Atoi(c_leng)
		if err != nil {
			self.TmplData["error"] = common.GetText(self.Lang, "The barcode length is Invalid.")
			return false
		}
		if i_leng < 1 {
			self.TmplData["error"] = common.GetText(self.Lang, "The barcode length is Invalid.")
			return false
		}
		if c_barc != "" {
			if len(c_barc) != i_leng {
				self.TmplData["error"] = common.GetText(self.Lang, "The BARCODE is not match LENGTH.")
				return false
			}
		}
		i_cleng = i_leng
	}
	i_qty, err := strconv.Atoi(c_iqty)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "The part qty must be a numeric.")
		return false
	}
	if i_qty < 1 {
		self.TmplData["error"] = common.GetText(self.Lang, "Qty must be more than zero.")
		return false
	}

	self.Sqlparas = append(self.Sqlparas, c_item)
	self.Sqlparas = append(self.Sqlparas, c_stat)
	self.Sqlparas = append(self.Sqlparas, c_name)
	self.Sqlparas = append(self.Sqlparas, c_desc)
	self.Sqlparas = append(self.Sqlparas, c_barc)
	self.Sqlparas = append(self.Sqlparas, i_cleng)
	self.Sqlparas = append(self.Sqlparas, i_qty)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)
	self.Flashparas = []interface{}{c_item, c_name}

	return true
}

func (self *SetKeyPartsObj) SqlExecute() bool {
	spRtnData := *common.FetchOneRowPtr(
		`sp_SetParts ?, ?, ?, ?, ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	if spRtnData.(common.SPReturn).Flag > 0 {
		self.TmplData["error"] = common.GetTextSP(self.Lang, spRtnData)
		return false
	}
	return true
}

func PartsSetHandler(ctx *web.Context) {
	self := new(SetKeyPartsObj)
	self.Ctx = ctx
	self.Url = "/setpart"
	self.Html = "setpart.html"
	self.Rightlist = []string{"setpart"}
	self.Flashstr = "Set Items: [ %v ] Part: [ %v ] finished."
	self.Do(self)
}

func (self *DeleteKeyPartsObj) ParameterCheck() bool {
	s_im := self.Ctx.Params["im"] // item
	s_st := self.Ctx.Params["st"] // station

	if s_im == "" || s_st == "" {
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_im)
	self.Sqlparas = append(self.Sqlparas, s_st)

	return true
}

func (self *DeleteKeyPartsObj) SqlQueryExecute() {
	err := common.ExecSqlNonRst(
		`DELETE FROM SFC_PARTSETTING 
		  WHERE ITEM=? 
		    AND STATION=?`,
		self.Usr.Conn, self.Sqlparas...)
	if err != nil {
		common.Application.SendMail(
			fmt.Sprintf("Delete Part Error: Item[%s], Station[%s], %v\n",
				self.Sqlparas[0].(string), self.Sqlparas[1].(string), err))
		return
	}
}

func DeleteKeyPartHandler(ctx *web.Context) {
	self := new(DeleteKeyPartsObj)
	self.Ctx = ctx
	self.Url = "/setpart"
	self.Rightlist = []string{"setpart"}
	self.DoRedirectUrl(self)
}
